package cn.pomelo.secondskill.service.impl;

import cn.hutool.core.lang.ObjectId;
import cn.pomelo.secondskill.common.Constants;
import cn.pomelo.secondskill.exception.SecondsKillException;
import cn.pomelo.secondskill.mapper.GoodsMapper;
import cn.pomelo.secondskill.model.Address;
import cn.pomelo.secondskill.model.Goods;
import cn.pomelo.secondskill.model.Orders;
import cn.pomelo.secondskill.rabbitMQ.Subscriber;
import cn.pomelo.secondskill.service.AddressService;
import cn.pomelo.secondskill.service.GoodsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    Subscriber<Orders> subscriber;

    @Resource
    private AddressService addressService;

    @Override
    public List<Goods> findAll() {
        return goodsMapper.selectAllGoods();
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return goodsMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Goods record) {
        return goodsMapper.insert(record);
    }

    @Override
    public int insertSelective(Goods record) {
        return goodsMapper.insertSelective(record);
    }

    @Override
    public Goods selectByPrimaryKey(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Goods record) {
        return goodsMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Goods record) {
        return goodsMapper.updateByPrimaryKey(record);
    }

    @Override
    public String selectGoodsNameById(Integer id) {
        return goodsMapper.selectGoodsNameById(id);
    }

    @Override
    public Orders doScKill(Integer goodsId, Integer userId, Integer state) throws SecondsKillException {
        if (state == 1) { // 订单已支付 修改商品库存
            Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
            Integer quantity = goods.getQuantity();
            if (quantity <= 0) {
                return null;
            }
            goods.setQuantity(quantity - 1);
            int update = goodsMapper.updateByPrimaryKey(goods);
            if (update <= 0) {
                return null;
            }
        }
        Orders scOrder = new Orders();
        scOrder.setId(ObjectId.next());
        scOrder.setUserId(userId);
        scOrder.setGoodsNumber(goodsId);
        // 支付状态
        scOrder.setState(state);
        Address defaultAdd = addressService.findDefaultAddByUserid(userId);
        if (defaultAdd != null) {
            scOrder.setAddressId(defaultAdd.getId());
        }
        if (state != 3) {
            // 将秒杀订单放到 RabbitMQ 队列
            subscriber.send(Constants.SECONDS_KILL_ORDER_QUEUE, "加入购物车成功", scOrder);
        }
        return scOrder;
    }

}
